package cn.lastcc.pwdmanage.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

import cn.lastcc.pwdmanage.R;
import cn.lastcc.pwdmanage.core.AesUtil;
import cn.lastcc.pwdmanage.core.CustomApp;
import cn.lastcc.pwdmanage.core.MD5;
import cn.lastcc.pwdmanage.core.PwdAction;
import cn.lastcc.pwdmanage.core.SerialUtil;
import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;
import cn.lastcc.pwdmanage.entity.PwdTag;

/**
 * 创建密码 Activity
 *
 * @author Added by baidongyang 2013-6-23
 * @version 15.5.23.1
 *
 */
public class CreatePwdActivity extends Activity {

	private static final String TAG = "CreatePwdActivity";

	private SerialUtil mSerialUtil = null;

    // 声明控件
    private CheckBox chkNum = null;
    private CheckBox chkLowLetter = null;
    private CheckBox chkUppLetter = null;
    private CheckBox chkSymbolChar = null;
    private EditText txtPwdLength = null;
    private Button btnCheckAll = null;
    private Button btnCheckInvert = null;
    private Button btnUnCheckAll = null;
    private Button btnGenerate = null;

    private TextView lblEditTag = null;
    private EditText txtEditTag = null;
    private TextView lblNewPwd = null;
    private EditText txtNewPwd = null;
    private Button btnSaveEdit = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSerialUtil = SerialUtil.getInstance(this);
        setContentView(R.layout.activity_create_pwd);
        // Show the Up button in the action bar.
//        setupActionBar();
        Intent intent=CreatePwdActivity.this.getIntent();
        Bundle bundle = intent.getExtras();

        // Modify by baidongyang 将密钥修改为用户明文口令，避免通过密文口令直接解密密码 2015-05-23
        CustomApp customApp = (CustomApp) CreatePwdActivity.this.getApplication();
        final String logonPwd = customApp.getUserPwd();

        if(bundle!=null&&bundle.getString("fromClassName").equals("PwdListActivity")){
        	this.setTitle("修改密码");
        	//获取控件
        	this.lblEditTag=(TextView)this.findViewById(R.id.lblEditTag_cpa);
        	this.txtEditTag=(EditText)this.findViewById(R.id.txtEditTag_cpa);
        	this.lblNewPwd=(TextView)this.findViewById(R.id.lblNewPwd_cpa);
        	this.txtNewPwd=(EditText)this.findViewById(R.id.txtNewPwd_cpa);
        	this.btnSaveEdit=(Button)this.findViewById(R.id.btnSaveEdit_cpa);
        	//显示控件
        	this.lblEditTag.setVisibility(View.VISIBLE);
        	this.txtEditTag.setVisibility(View.VISIBLE);
        	this.lblNewPwd.setVisibility(View.VISIBLE);
        	this.txtNewPwd.setVisibility(View.VISIBLE);
        	// 显示密码
            this.txtNewPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        	this.btnSaveEdit.setVisibility(View.VISIBLE);
        	//为控件赋值
        	String pwdTagId=bundle.getString("pwdTagId");
        	Info info = null;
            try {
                info = mSerialUtil.getInfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (null != info) {
            	List<PwdTag> pwdTagList = info.getPwdTagList();
                for (int i = 0, j = pwdTagList.size(); i < j; i++) {
                	PwdTag pt=pwdTagList.get(i);
                	if(pt.getId().equals(pwdTagId)){
                	    byte[] salt = pt.getSalt();
                		this.txtEditTag.setText(new String(AesUtil.decrypt(AesUtil.parseHexStr2Byte(pt.getTagName()), logonPwd, salt)));
                		String pwd = new String(AesUtil.decrypt(AesUtil.parseHexStr2Byte(pt.getPwd()), logonPwd, salt));
                		this.txtNewPwd.setText(pwd);
                		break;
                	}
                }
            }

            //为控件绑定事件
            // 保存按钮单击事件
            this.btnSaveEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 非空校验
                    if ("".equals(CreatePwdActivity.this.txtEditTag.getText().toString())) {
                        Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_savePwdTagEmpty, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if ("".equals(CreatePwdActivity.this.txtNewPwd.getText().toString())) {
                        Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_saveNewPwdEmpty, Toast.LENGTH_SHORT).show();
                        return;
                    }
                	Intent intent=CreatePwdActivity.this.getIntent();
                    Bundle bundle = intent.getExtras();
                	String pwdTagId=bundle.getString("pwdTagId");
                	Info info = null;
                    try {
                        info = mSerialUtil.getInfo();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                	 if (null != info) {
                	     // 生成新的 PwdTag 对象
                     	List<PwdTag> pwdTagList = info.getPwdTagList();
                     	CustomApp customApp = (CustomApp) CreatePwdActivity.this.getApplication();
                     	final String tagName = CreatePwdActivity.this.txtEditTag.getText().toString().trim();
                     	final String newPwd = CreatePwdActivity.this.txtNewPwd.getText().toString();
                     	if (null == pwdTagId) {
                     	    pwdTagList.add(createPwdTag(newPwd, tagName, customApp.getUserPwd()));
                     	}
                     	// 修改已有的 PwdTag 对象
                     	else {
                            for (int i = 0, j = pwdTagList.size(); i < j; i++) {
                            	PwdTag pt=pwdTagList.get(i);
                            	if(pt.getId().equals(pwdTagId)){
                            	    byte[] salt = new byte[IConstant.LENGTH_SALT];
                            	    AesUtil.generateSalt(salt);
                            	    pt.setSalt(salt);
                            		pt.setTagName(AesUtil.parseByte2HexStr((AesUtil.encrypt(tagName, logonPwd, salt))));
                            		pt.setPwd(AesUtil.parseByte2HexStr((AesUtil.encrypt(newPwd, logonPwd, salt))));
                            		pt.setModifyTimes(pt.getModifyTimes() + 1);
                            		break;
                            	}
                            }
                     	}
                         info.setPwdTagList(pwdTagList);
                         try {
                             mSerialUtil.setInfo(info);
                             Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_modifySavePwdSuccess, Toast.LENGTH_SHORT).show();
                             CreatePwdActivity.this.finish();
                         } catch (Exception e) {
                             e.printStackTrace();
                             Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_savePwdFailed, Toast.LENGTH_SHORT).show();
                         }
                     }
                }
            });
        }else{
        	this.setTitle("生成随机密码");
        }
        // 根据 ID 获取控件对象
        this.chkNum = (CheckBox) this.findViewById(R.id.chkNum_cpa);
        this.chkLowLetter = (CheckBox) this.findViewById(R.id.chkLowLetter_cpa);
        this.chkUppLetter = (CheckBox) this.findViewById(R.id.chkUppLetter_cpa);
        this.chkSymbolChar = (CheckBox) this.findViewById(R.id.chkSymbolChar_cpa);
        this.txtPwdLength = (EditText) this.findViewById(R.id.txtPwdLength_cpa);
        this.btnCheckAll = (Button) this.findViewById(R.id.btnCheckAll_cpa);
        this.btnCheckInvert = (Button) this.findViewById(R.id.btnCheckInvert_cpa);
        this.btnUnCheckAll = (Button) this.findViewById(R.id.btnUnCheckAll_cpa);
        this.btnGenerate = (Button) this.findViewById(R.id.btnGenerate_cpa);
        // 全选按钮单击事件
        this.btnCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chkNum.setChecked(true);
                chkLowLetter.setChecked(true);
                chkUppLetter.setChecked(true);
                chkSymbolChar.setChecked(true);
            }
        });
        // 反选按钮单击事件
        this.btnCheckInvert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chkNum.setChecked(!chkNum.isChecked());
                chkLowLetter.setChecked(!chkLowLetter.isChecked());
                chkUppLetter.setChecked(!chkUppLetter.isChecked());
                chkSymbolChar.setChecked(!chkSymbolChar.isChecked());
            }
        });
        // 全不选按钮单击事件
        this.btnUnCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chkNum.setChecked(false);
                chkLowLetter.setChecked(false);
                chkUppLetter.setChecked(false);
                chkSymbolChar.setChecked(false);
            }
        });
        // 生成密码按钮单击事件
        this.btnGenerate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (!chkNum.isChecked()
                        && !chkLowLetter.isChecked()
                        && !chkUppLetter.isChecked()
                        && !chkSymbolChar.isChecked()) {
                    Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_notCheck, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (txtPwdLength.length() == 0) {
                    Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_notPwdLength, Toast.LENGTH_SHORT).show();
                    return;
                }
                // 计算权重
                int weight = 0;
                if (chkNum.isChecked()) {
                    weight += 1;
                }
                if (chkLowLetter.isChecked()) {
                    weight += 2;
                }
                if (chkUppLetter.isChecked()) {
                    weight += 4;
                }
                if (chkSymbolChar.isChecked()) {
                    weight += 8;
                }
                final PwdAction pwdAction = new PwdAction();
                final String generatePwd = pwdAction.generatePwd(weight, Integer.parseInt(txtPwdLength.getText().toString()));
                Intent intent=CreatePwdActivity.this.getIntent();
                Bundle bundle = intent.getExtras();
                if(bundle!=null&&bundle.getString("fromClassName").equals("PwdListActivity")){ // 修改密码
                	// 创建对话框显示密码并提示用户操作
                    Dialog pwdDialog = new AlertDialog.Builder(CreatePwdActivity.this)
                        .setMessage(generatePwd)
                        .setTitle(R.string.msg_createPwdActivity_dialogPwdTitle)
                        .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            	CreatePwdActivity.this.txtNewPwd.setText(generatePwd);
                            	dialog.cancel();
                            }
                        })
                        .setNeutralButton("重新生成", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 模拟按钮单击
                                btnGenerate.performClick();
                            }
                        })
                        .setNegativeButton(R.string.str_globe_Cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .create();
                    pwdDialog.show();
                }else{ // 创建密码
                	// 创建对话框显示密码并提示用户操作
                    Dialog pwdDialog = new AlertDialog.Builder(CreatePwdActivity.this)
                        .setMessage(generatePwd)
                        .setTitle(R.string.msg_createPwdActivity_dialogPwdTitle)
                        .setPositiveButton(R.string.str_globe_Save, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                final EditText __txtTag = new EditText(CreatePwdActivity.this);
                                new AlertDialog.Builder(CreatePwdActivity.this)
                                .setTitle("请输入标签名")
                                .setView(__txtTag)
                                .setPositiveButton(R.string.str_globe_Save, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    	MD5 md5 = new MD5();
                                        // 非空
                                        if ("".equals(__txtTag.getText().toString())) {
                                            try {
                                                Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                                field.setAccessible(true);
                                                // 将mShowing变量设为false，表示对话框已关闭，用于阻止关闭对话框
                                                field.set(dialog, false);
                                                dialog.dismiss();
                                            } catch (NoSuchFieldException e) {
                                                e.printStackTrace();
                                            } catch (IllegalArgumentException e) {
                                                e.printStackTrace();
                                            } catch (IllegalAccessException e) {
                                                e.printStackTrace();
                                            }
                                            Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_savePwdTagEmpty, Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        try {
                                            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                            field.setAccessible(true);
                                            // 将mShowing变量设为true，解除阻止关闭对话框
                                            field.set(dialog, true);
                                            dialog.dismiss();
                                        } catch (NoSuchFieldException e) {
                                            e.printStackTrace();
                                        } catch (IllegalArgumentException e) {
                                            e.printStackTrace();
                                        } catch (IllegalAccessException e) {
                                            e.printStackTrace();
                                        }
                                        Info info = null;
                                        try {
                                            info = mSerialUtil.getInfo();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Toast.makeText(v.getContext(), "警告：文件读取失败，将生成新文件替代原有文件！", Toast.LENGTH_SHORT);
                                        }
                                        if (null == info) {
                                            info = new Info();
	                                        CustomApp customApp = (CustomApp) CreatePwdActivity.this.getApplication();
	                                        info.setVersionCode(customApp.getVersionCode());
	                                        info.setVersionName(customApp.getVersionName());
	                                        info.setFileVersion(IConstant.INFO_CUR_VERSION_STR);
	                                        info.setUserPassword(md5.cell32(customApp.getUserPwd()));
                                        }
                                        PwdTag pwdTag = createPwdTag(generatePwd, __txtTag.getText().toString().trim(), logonPwd);
                                        info.getPwdTagList().add(pwdTag);
                                        try {
                                            mSerialUtil.setInfo(info);
                                            Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_savePwdSuccess, Toast.LENGTH_SHORT).show();
                                            CreatePwdActivity.this.finish();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Toast.makeText(v.getContext(), R.string.msg_createPwdActivity_savePwdFailed, Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
                                            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                            field.setAccessible(true);
                                            field.set(dialog, true);
                                            dialog.dismiss();
                                        } catch (NoSuchFieldException e) {
                                            e.printStackTrace();
                                        } catch (IllegalArgumentException e) {
                                            e.printStackTrace();
                                        } catch (IllegalAccessException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                })
                                .show();
                            }
                        })
                        .setNeutralButton("重新生成", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 模拟按钮单击
                                btnGenerate.performClick();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .create();
                    pwdDialog.show();
                }
            }
        });
    }

    /**
     * 创建 PwdTag 对象<br/>
     * 一般在生成新密码时建议调用本方法，而不是手工创建 PwdTag 对象，<br/>
     * 因为本方法会按照约定预置好返回的 PwdTag 对象中的各个属性。
     * @param pwd 要保存的密码(明文)
     * @param tagName 标签名(明文)
     * @param userPwd 当前用户登陆密码(明文；用于对前两个参数做加密)
     * @return 处理完所有属性的 PwdTag 对象，可以直接保存到 Info.pwdTagList 中
     * @author Added by baidongyang 2013-6-30
     */
    private PwdTag createPwdTag (final String pwd, final String tagName, String userPwd) {
        PwdTag pwdTag = new PwdTag();
        String tagText = tagName;
        // 生成盐值
        byte[] salt = new byte[IConstant.LENGTH_SALT]; // salt长度是 32*8 = 256bit.
        AesUtil.generateSalt(salt);
        // 保存盐值
        pwdTag.setSalt(salt);
        // 加密标签
        byte [] encryptResult = AesUtil.encrypt(tagText, userPwd, salt);
        final String __encTag = AesUtil.parseByte2HexStr(encryptResult);
//        Log.d("bxDebug", "__encTag: " + __encTag);
        pwdTag.setTagName(__encTag);
        // 加密生成的密码
        encryptResult = AesUtil.encrypt(pwd, userPwd, salt);
        final String __encPwd = AesUtil.parseByte2HexStr(encryptResult);
//        Log.d("bxDebug", "__encPwd: " + __encPwd);
        pwdTag.setPwd(__encPwd);
        pwdTag.setCreateDate(new Date());
        pwdTag.setModifyTimes(0);
        return pwdTag;
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

}
